/**
 * Creator:     JYW
 * CreatDate:   2019-04-10
 * descripts：  护士办理出院结算
*/
import React, { Component } from 'react';
import { Modal, message, Row, Col, Tooltip, Select, DatePicker, TimePicker, Input } from 'antd';
import { $http } from '../../../containers/config/https';
import PatientInfo from '../Patient/PatientInfo';
import moment from 'moment';

let user;
var patientData;
class Discharge extends Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			admID: '',
			disCondition: [],
			recallReason: [],
			needCareCondition: [],
			selCondition: '',
			dieFlag: 'N',
			admDocChargeDate: '',
			admDocChargeTime: '',
			admNurChargeDate: '',
			admNurChargeTime: '',
			patDeceasedDate: '',
			patDeceasedTime: '',
			patientInfo: '',
			admDocChargeDesc: '',
			admNurChargeDesc: '',
			okText: '医疗结算',
			okDisable: false,
			disType: '1', // disType 1 医疗结算 2 撤销医疗结算 3 护士办理出院 4 护士撤销出院
			disInfoClass: '',
			recallID: '',
			patStatus: '',
			discharge: '',
			formatDateType: true,
			formatTimeType: true,
			openadmDocChargeDate: false,
			openadmDocChargeTime: false,
			openpatDeceasedDate: false,
			openpatDeceasedTime: false,
			openadmNurChargeDate: false,
			openadmNurChargeTime: false,
			controlFlag: false // 需关注是否控制出院
		};

		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
	}

	//每隔两个字符串添加一个冒号
	strInsert = (str, length) => {
		if (str && typeof (str) === 'string') {
			var reg = new RegExp('\\w{1,' + length + '}', 'g');
			let ma = str.match(reg);
			return ma.join(':');
		}
		return str;
	};

	handleOk = () => {
		let code = '04050002';
		let paramObj = {};
		if (user.groupDesc.indexOf('护士') > -1) {
			code = '04050003';
			paramObj.admNurChargeDate = moment(this.state.admNurChargeDate).format('YYYY-MM-DD');
			// paramObj.admNurChargeTime = moment(this.state.admNurChargeTime).isValid()
			// 	? moment(this.state.admNurChargeTime).format('HH:mm:ss')
			// 	: this.state.admNurChargeTime;
			paramObj.admNurChargeTime = moment(this.state.admNurChargeTime).isValid()
				? moment(this.state.admNurChargeTime).format('HH:mm:ss')
				: this.strInsert(this.state.admNurChargeTime, 2);
		} else {
			if (this.state.dieFlag === 'Y') {
				paramObj.patDeceasedDate = moment(this.state.patDeceasedDate).format('YYYY-MM-DD');
				paramObj.patDeceasedTime = moment(this.state.patDeceasedTime).isValid()
					? moment(this.state.patDeceasedTime).format('HH:mm:ss')
					: this.strInsert(this.state.patDeceasedTime, 2);
			}
			if (this.state.disType !== '2') {
				paramObj.admDocChargeDate = moment(this.state.admDocChargeDate).format('YYYY-MM-DD');
				paramObj.admDocChargeTime = moment(this.state.admDocChargeTime).isValid()
					? moment(this.state.admDocChargeTime).format('HH:mm:ss')
					: this.strInsert(this.state.admDocChargeTime, 2);
				paramObj.disConditionID = this.state.selCondition;
			} else {
				paramObj.admDocChargeDate = '';
				paramObj.admDocChargeTime = '';
				paramObj.disConditionID = '';
			}
		}
		paramObj.admID = this.state.admID ? this.state.admID : patientData.admID;
		paramObj.userID = user.userID;
		paramObj.discharge = this.state.discharge;
		if (this.state.disType === '2' || this.state.disType === '4') {
			paramObj.cancelDis = this.state.disType;
		} else {
			if (this.state.selCondition === '') {
				message.error('请选择出院原因!');
				return;
			}
		}

		let data = { params: [] };
		data.params.push(paramObj);
		$http.post('urlDeault', this, {
			code: code,
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					message.success(res.errorMessage);
					this.setState({
						visible: false
					});
					if (this.props.updateData) {
						this.props.updateData({
							admID: '',
							patID: '',
							selectBedId: '',
							otherSelectId: '',
							mouseInID: '',
							roomLoading: true
						});
					}
					if (this.props.getPatients) {
						this.props.getPatients();
						if (this.props.child) {
							this.props.child.getRooms();
						}
					}
				}
			}
		});
	};

	handleCancel = () => {
		message.info('操作已取消！');
		this.setState({
			visible: false
		});
	};

	onConditionChange = (value, option) => {
		this.setState({
			selCondition: value,
			dieFlag: option.props.dieFlag
		});
	};

	onRecallChange = (value, option) => {
		this.setState({
			recallID: value
		});
	};

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}
	componentWillUnmount() {
		this.setState = (state, callback) => {
			return;
		};
	}

	/**
		*  获取患者基本信息
	 */
	getPatientInfo(admID) {
		let data = {
			params: [
				{
					admID: admID ? admID : patientData.admID,
					hospID: user.hospID
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '04020007',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					let patientInfo = res.result;
					let admDocChargeDate = patientInfo.admInfo.admDocChargeDate,
						admDocChargeTime = patientInfo.admInfo.admDocChargeTime;
					let admNurChargeDate = patientInfo.admInfo.admNurChargeDate,
						admNurChargeTime = patientInfo.admInfo.admNurChargeTime;
					if (patientInfo.admInfo.admDocChargeDate === '') {
						admDocChargeDate = moment(new Date(), 'YYYY-MM-DD');
						admDocChargeTime = moment(new Date(), 'HH:mm');
					} else {
						if (user.groupDesc.indexOf('护士') > -1 && patientInfo.admInfo.admNurChargeDate === '') {
							//护士点击出院
							admNurChargeDate = moment(new Date(), 'YYYY-MM-DD');
							admNurChargeTime = moment(new Date(), 'HH:mm');
						}
					}

					let okText = '确定',
						okDisable = false,
						disType = '1';
					if (
						user.groupDesc.indexOf('护士') < 0 &&
						user.groupDesc.indexOf('医生') < 0 &&
						user.groupDesc.indexOf('医师') < 0
					) {
						//非护士医生
					} else {
						if (user.groupDesc.indexOf('护士') > -1) {
							(okText = '出院'), (disType = '3');
							//护士
							if (patientInfo.admInfo.admDocChargeDate === '') {
								okDisable = true;
							}
							if (patientInfo.admInfo.admNurChargeDate !== '') {
								(okText = '出院召回'), (disType = '4');
							}
						} else {
							okText = '医疗结算';
							if (patientInfo.admInfo.admDocChargeDate !== '') {
								(okText = '撤销医疗结算'), (disType = '2');
							}
							if (patientInfo.admInfo.admNurChargeDate !== '') {
								(okText = '出院召回'), (disType = '4');
								okDisable = true;
							}
						}
					}
					let patDeceased = patientInfo.basicInfo.patDeceased;
					this.setState({
						patientInfo: patientInfo,
						selCondition: patientInfo.admInfo.admDisConditionID,
						dieFlag: patDeceased,
						admDocChargeDate: admDocChargeDate,
						admDocChargeTime: admDocChargeTime,
						admNurChargeDate: admNurChargeDate,
						admNurChargeTime: admNurChargeTime,
						patDeceasedDate: patientInfo.basicInfo.patDeceasedDate,
						patDeceasedTime: patientInfo.basicInfo.patDeceasedTime,
						discharge: patientInfo.admInfo.discharge,
						admDocChargeDesc: patientInfo.admInfo.admDocChargeDesc,
						admNurChargeDesc: patientInfo.admInfo.admNurChargeDesc,
						okText: okText,
						okDisable: okDisable,
						disType: disType
					});
				} else {
					message.error('获取病人基本信息失败!:' + res.errorMessage);
				}
			}
		});
	}

	getDisCondition = () => {
		let data = {
			params: [
				{
					typeCode: 'recall'
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '04050012',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					this.setState({
						disCondition: res.result.disCondition,
						recallReason: res.result.recallReason,
						dischargeArr: res.result.dischargeArr
					});
					this.getNeedCareCondition();
				} else {
					message.error('获取出院条件失败!:' + res.errorMessage);
				}
			}
		});
	};

	getNeedCareCondition = () => {
		let { controlFlag } = this.state;
		let data = {
			params: [
				{
					power: 'discharge',
					admID: this.state.admID ? this.state.admID : patientData.admID,
					deptType: user.groupDesc.indexOf('护士') < 0 ? 'D' : 'N'
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '04050005',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					console.log('getNeedCareCondition', res);
					let len = res.result.needCareAry.length;
					for (let i = 0; i < len; i++) {
						if (res.result.needCareAry[i].controlFlag == '1') {
							controlFlag = true;
							break;
						}
					}
					this.setState({
						needCareCondition: res.result.needCareAry,
						controlFlag
					});
				} else {
					message.error(':' + res.errorMessage);
				}
			}
		});
	};

	//需关注跳转
	handparameter = (item) => {
		// window.location.href='/04030001';
		// console.log(item.jumpPage)
		if (item.jumpPage) this.props.history.push(item.jumpPage);
	};

	onDateTimeChange = (flag, datetime, datetimeString) => {
		if (flag === 'admNurChargeTime' || flag === 'admDocChargeTime' || flag === 'patDeceasedTime') {
			datetimeString = datetimeString + '00'
		};
		this.setState({
			[flag]: datetimeString
		});
	};

	showModal = (admID) => {
		this.setState(
			{
				visible: true,
				admID: admID
			},
			() => {
				this.getPatientInfo(this.state.admID);
				this.getDisCondition();
			}
		);
	};

	onDischarge = (value, option) => {
		this.setState({
			discharge: option
		});
	};

	//日期面板打开/关闭
	handleOnOpenChangeDate = (code, status) => {
		if (status) {
			this.setState({
				formatDateType: false,
				['open' + code]: true
			});
		} else {
			this.setState({
				formatDateType: true,
				['open' + code]: false
			});
		}
	};

	handleOnOpenChangeTime = (code, status) => {
		if (status) {
			this.setState({
				formatTimeType: false,
				['open' + code]: true
			});
		} else {
			this.setState({
				formatTimeType: true,
				['open' + code]: false
			});
		}
	};

	//时间框回车
	timeBlur = (e, code) => {
		var e = window.event || e;
		if (e.keyCode == 13) {
			this.setState({
				// ['open' + code]: false,
				// formatTimeType: true
			});
		}
	};

	render() {
		let disable =
			user.groupDesc.indexOf('护士') < 0 && user.groupDesc.indexOf('医生') < 0 && user.groupDesc.indexOf('医师') < 0;
		let recall = [];
		this.state.recallReason.map((item) => {
			recall.push(
				<Select.Option value={item.id} key={item.id}>
					{item.descripts}
				</Select.Option>
			);
		});

		var dischargeArr = [];
		this.state.dischargeArr &&
			this.state.dischargeArr.map((item, index) => {
				dischargeArr.push(
					<Select.Option key={index} value={item.id}>
						{item.descripts}
					</Select.Option>
				);
			});
		return (
			<Modal
				title="出院"
				width="1100px"
				className="Discharge"
				visible={this.state.visible}
				onOk={this.handleOk}
				onCancel={this.handleCancel}
				okText={this.state.okText}
				okButtonProps={{
					disabled: this.state.controlFlag ? true : this.state.okDisable
				}}
				style={{
					height: '416px',
					background: '#FFFFFF',
					borderRadius: '6px',
					top: '247px'
				}}
				cancelText="取消"
				destroyOnClose
				maskClosable={false}
			>
				<div>
					<Row>
						<Row style={{ width: '100%', height: '40px', lineHeight: '30px' }}>
							<PatientInfo admID={patientData.admID} ref="PatientInfo" />
						</Row>
						<Row className="Discharge disPanel">
							<Col span={9} className="Discharge needAttention">
								{this.state.needCareCondition.length > 0 ? (
									this.state.needCareCondition.map((item, index) => {
										return (
											<div onClick={this.handparameter.bind(this, item)} key={index}>
												<div>
													{item.abnorDesc}医嘱{item.number}条
												</div>
												<div style={{ width: 'calc(100% - 20px)', marginLeft: '20px', border: '1px solid #ccc' }}>
													<div style={{
														display: 'flex',
														flexDirection: 'row',
														borderBottom: '1px solid #999'
													}}>
														<div style={{ width: '100px', borderRight: '1px solid #ccc' }}>开单科室</div>
														<div style={{ width: 'calc(100% - 202px)', borderRight: '1px solid #ccc' }}>医嘱名称</div>
														<div style={{ width: '100px' }}> 时间</div>
													</div>
													{/*
														* @ByShizi: 加多一个开单科室
														* Create 2022-09-28
													*/}
													{item.ordInfoAry.map((orderitem) => {
														return (
															<div
																style={{
																	display: 'flex',
																	flexDirection: 'row',
																	borderBottom: '1px solid #999'
																}}
															>
																<div style={{ width: '100px', borderRight: '1px solid #ccc' }}>
																	<Tooltip title={orderitem.ordLocDesc}>
																		<span className='ellipsis' style={{ width: '100%', display: 'inline-block' }}>{orderitem.ordLocDesc}</span>
																	</Tooltip>
																</div>
																<div style={{ width: 'calc(100% - 202px)', borderRight: '1px solid #ccc' }}>
																	<Tooltip title={orderitem.medDesc}>
																		<span className='ellipsis' style={{ width: '100%', display: 'inline-block' }}>{orderitem.medDesc}</span>
																	</Tooltip>
																</div>
																<div
																	style={{ display: 'flex', flexDirection: 'column', width: '100px' }}
																>
																	<Tooltip title={orderitem.execItem.length == 0 ? orderitem.ordStartDateTime : (
																		orderitem.execItem.map((execItem) => {
																			return (
																				<span>
																					{execItem.execReqDateTime}{' '}
																				</span>
																			);
																		})
																	)}>
																		{orderitem.execItem.length == 0 ? (
																			<span className='ellipsis' style={{ width: '100%', display: 'inline-block' }}>{orderitem.ordStartDateTime}</span>
																		) : (
																			<div style={{ width: '100%' }} className='ellipsis'>
																				{orderitem.execItem.map((execItem) => {
																					return (
																						<span>
																							{execItem.execReqDateTime}{' '}
																						</span>
																					);
																				})}
																			</div>
																		)}
																	</Tooltip>

																</div>
															</div>
														);
													})}
												</div>
											</div>
										);
									})
								) : null}
							</Col>
							<Col span={15} className="Discharge disInfo">
								<Row>
									<Col span={5} style={{ lineHeight: '30px' }}>
										预出院日期:
									</Col>
									<Col span={7}>
										<DatePicker
											style={{ width: '100%' }}
											separator="-"
											onChange={this.onDateTimeChange.bind(this, 'admDocChargeDate')}
											value={
												this.state.admDocChargeDate === '' ? null : (
													moment(this.state.admDocChargeDate, 'YYYY-MM-DD')
												)
											}
											format={this.state.formatDateType ? 'YYYY-MM-DD' : 'YYYYMMDD'}
											onOpenChange={(status) =>
												this.handleOnOpenChangeDate('admDocChargeDate', status)}
											open={this.state.openadmDocChargeDate}
											disabled={user.groupDesc.indexOf('护士') > -1}
											allowClear={false}
										/>
									</Col>
									<Col span={5} style={{ lineHeight: '30px' }}>
										预出院时间:
									</Col>
									<Col span={7}>
										<TimePicker
											style={{ width: '100%' }}
											onChange={this.onDateTimeChange.bind(this, 'admDocChargeTime')}
											value={
												this.state.admDocChargeTime === '' ? null : (
													moment(this.state.admDocChargeTime, 'HH:mm')
												)
											}
											disabled={user.groupDesc.indexOf('护士') > -1}
											format={this.state.formatTimeType ? 'HH:mm' : 'HHmm'}
											onOpenChange={(status) =>
												this.handleOnOpenChangeTime('admDocChargeTime', status)}
											onKeyDown={(e) => this.timeBlur(e, 'admDocChargeTime')}
											open={this.state.openadmDocChargeTime}
											allowClear={false}
											separator=":"
										/>
									</Col>
								</Row>
								<Row className="Discharge row">
									<Col span={5} style={{ lineHeight: '30px' }}>
										{' '}
										离院方式:
									</Col>
									<Col span={7}>
										<Select
											style={{ width: '100%' }}
											disabled={user.groupDesc.indexOf('护士') > -1}
											onChange={this.onDischarge.bind(this, 'discharge')}
											value={this.state.discharge}
										>
											{dischargeArr}
										</Select>
									</Col>
									<Col span={5} style={{ lineHeight: '30px' }}>
										离院原因:
									</Col>
									<Col span={7}>
										<Select
											style={{ width: '100%' }}
											disabled={user.groupDesc.indexOf('护士') > -1}
											onChange={this.onConditionChange}
											value={this.state.selCondition}
										>
											{this.state.disCondition.map((condition) => {
												return (
													<Select.Option
														value={condition.id}
														key={condition.id}
														dieFlag={condition.dieFlag}
													>
														{condition.descripts}
													</Select.Option>
												);
											})}
										</Select>
									</Col>
								</Row>
								{this.state.dieFlag === 'Y' ? (
									<Row className="Discharge row">
										<Col span={5} style={{ lineHeight: '30px' }}>
											{' '}
											死亡日期:{' '}
										</Col>
										<Col span={7}>
											<DatePicker
												style={{ width: '100%' }}
												onChange={this.onDateTimeChange.bind(this, 'patDeceasedDate')}
												value={
													this.state.patDeceasedDate === '' ? null : (
														moment(this.state.patDeceasedDate, 'YYYY-MM-DD')
													)
												}
												format={this.state.formatDateType ? 'YYYY-MM-DD' : 'YYYYMMDD'}
												onOpenChange={(status) =>
													this.handleOnOpenChangeDate('patDeceasedDate', status)}
												open={this.state.openpatDeceasedDate}
												disabled={user.groupDesc.indexOf('护士') > -1}
											/>
										</Col>
										<Col span={5} style={{ lineHeight: '30px' }}>
											{' '}
											死亡时间:{' '}
										</Col>
										<Col span={7}>
											<TimePicker
												style={{ width: '100%' }}
												onChange={this.onDateTimeChange.bind(this, 'patDeceasedTime')}
												value={
													this.state.patDeceasedTime === '' ? null : (
														moment(this.state.patDeceasedTime, 'HH:mm:ss')
													)
												}
												format={this.state.formatTimeType ? 'HH:mm' : 'HHmm'}
												onOpenChange={(status) =>
													this.handleOnOpenChangeTime('patDeceasedTime', status)}
												onKeyDown={(e) => this.timeBlur(e, 'patDeceasedTime')}
												open={this.state.openpatDeceasedTime}
												disabled={user.groupDesc.indexOf('护士') > -1}
											/>
										</Col>
									</Row>
								) : (
									''
								)}

								<Row>
									<Col span={5} style={{ lineHeight: '30px' }} className="Discharge row">
										{' '}
										操作医生:{' '}
									</Col>
									<Col span={7} className="Discharge row">
										<Input
											style={{ width: '100%' }}
											value={
												this.state.admDocChargeDesc === '' ? (
													user.name
												) : (
													this.state.admDocChargeDesc
												)
											}
											disabled={true}
										/>
									</Col>

									<Col span={5} className="Discharge row">
										{' '}
										出院日期:
									</Col>
									<Col span={7} className="Discharge row">
										<DatePicker
											style={{ width: '100%' }}
											onChange={this.onDateTimeChange.bind(this, 'admNurChargeDate')}
											value={
												this.state.admNurChargeDate === '' ? null : (
													moment(this.state.admNurChargeDate, 'YYYY-MM-DD')
												)
											}
											format={this.state.formatDateType ? 'YYYY-MM-DD' : 'YYYYMMDD'}
											onOpenChange={(status) =>
												this.handleOnOpenChangeDate('admNurChargeDate', status)}
											open={this.state.openadmNurChargeDate}
											disabled={user.groupDesc.indexOf('护士') < 0}
										/>
									</Col>
									<Col span={5} className="Discharge row" style={{ lineHeight: '30px' }}>
										{' '}
										出院时间:{' '}
									</Col>
									<Col span={7} className="Discharge row">
										<TimePicker
											style={{ width: '100%' }}
											onChange={this.onDateTimeChange.bind(this, 'admNurChargeTime')}
											value={
												this.state.admNurChargeTime === '' ? null : (
													moment(this.state.admNurChargeTime, 'HH:mm')
												)
											}
											format={this.state.formatTimeType ? 'HH:mm' : 'HHmm'}
											onOpenChange={(status) =>
												this.handleOnOpenChangeTime('patDeceasedTime', status)}
											onKeyDown={(e) => this.timeBlur(e, 'patDeceasedTime')}
											open={this.state.openpatDeceasedTime}
											disabled={user.groupDesc.indexOf('护士') < 0}
										/>
									</Col>

									{/* </Row>
                                <Row className="Discharge row" > */}
									<Col span={5} className="Discharge row">
										{' '}
										操作护士:{' '}
									</Col>
									<Col span={7} className="Discharge row">
										<Input
											style={{ width: '100%' }}
											value={
												this.state.admNurChargeDesc !== '' &&
													this.state.admNurChargeDesc === '' ? (
													user.name
												) : (
													this.state.admNurChargeDesc
												)
											}
											disabled={true}
										/>
									</Col>
									<Col span={5} className="Discharge row" style={{ lineHeight: '30px' }}>
										{' '}
										召回原因:{' '}
									</Col>
									<Col span={7} className="Discharge row">
										<Select
											style={{ width: '100%' }}
											disabled={this.state.disType != '4'}
											onChange={this.onRecallChange}
											value={this.state.recallID}
										>
											{recall}
										</Select>
									</Col>
								</Row>
							</Col>
						</Row>
					</Row>
				</div>
			</Modal>
		);
	}
}
export default Discharge;
